import React, { useState } from 'react'
import 'amis/lib/themes/cxd.css'
import { Schema } from 'amis/lib/types'
import { ButtonSchema, uuidv4 } from 'amis'
import amisRender from '@/components/amis/amisRender'
import { EditorControlSchema } from 'amis/lib/renderers/Form/Editor'

/**
 * 实时代码编辑器
 */
const RealTimeCodeEditor = (props: { code: Schema }): JSX.Element => {
	const [realTimeCodeEditorId, setRealTimeCodeEditorId] = useState(uuidv4())
	const [code, setCode] = useState(props.code)
	const realTimeCodeEditorSchema = {
		type: 'wrapper',
		style: {
			padding: '0px',
		} as React.CSSProperties,
		body: {
			label: '',
			type: 'button',
			icon: 'fa-solid fa-book',
			actionType: 'drawer',
			drawer: {
				title: '编辑代码（支持编辑实时预览-Esc退出）',
				closeOnEsc: true,
				resizable: true,
				actions: [],
				body: {
					type: 'editor',
					name: 'editor',
					size: 'xxl',
					allowFullscreen: true,
					value: code,
					options: {
						automaticLayout: true,
					},

					language: 'json',
					onEvent: {
						change: {
							actions: [
								{
									actionType: 'custom',
									script: (context: any, doAction: any, event: any) => {
										const newValue = event.data.value
										setCode(newValue)
									},
								},
							],
						},
					},
				} as EditorControlSchema,
			},
		} as ButtonSchema,
	}
	const realTimeCodeEditorEl = amisRender.render(realTimeCodeEditorSchema)
	const realTimeCodeEditorCssProps: React.CSSProperties = {
		position: 'fixed',
		right: '20px',
		zIndex: 99999,
		top: '50%',
	}

	const amisRendererSchema = {
		type: 'page',
		style: {
			padding: '0px',
		} as React.CSSProperties,
		body: {
			type: 'amis',
			schema: code,
		},
	}
	return (
		<>
			<div id={realTimeCodeEditorId} style={realTimeCodeEditorCssProps}>
				{realTimeCodeEditorEl}
			</div>
			{amisRender.render(amisRendererSchema)}
		</>
	)
}

export default RealTimeCodeEditor
